package com.yowasa.xiuxian.util;

import com.ruiyun.jvppeteer.core.Puppeteer;
import com.ruiyun.jvppeteer.core.browser.Browser;
import com.ruiyun.jvppeteer.core.browser.BrowserFetcher;
import com.ruiyun.jvppeteer.core.page.ElementHandle;
import com.ruiyun.jvppeteer.core.page.Page;
import com.ruiyun.jvppeteer.options.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ExecutionException;

public class PagescreenshotUtil {

//    public static void main(String[] args) throws Exception {
//        // 创建一个 Configuration 对象
//        Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
//
//
//        // 设置模板文件所在的路径
//        configuration.setDirectoryForTemplateLoading(new File("./src/main/java/com/yowasa/xiuxian/image/html"));
//
//        // 加载模板文件
//        Template template = configuration.getTemplate("template.html");
//
//        // 创建一个数据模型
//        Map<String, Object> dataModel = new HashMap<>();
////        dataModel.put("username", "Hello, World!");
////        dataModel.put("mylist", Lists.newArrayList("aaa","bbb","ccc"));
//        UserBO bo = new UserBO();
//        bo.setName("aaaa");
//        bo.setStage(1);
//        bo.setLevel(0);
//        bo.setUserAttr(UserAttr.genAttr());
//        UserBattle userBattle = UserBattle.genBattleAttr(bo.getUserAttr());
//        bo.setUserBattle(userBattle);
//        bo.setUserOriginBattle(userBattle);
//        bo.setElement(ElementEnum.genLingGen());
//        bo.setUserConfig(new UserConfig());
//        bo.setStartAt(new Date());
//        bo.setAge(DateXUtil.START_AGE);
//        bo.buildBaseInfo();
//        String mental = "111";
//        String lingGen = "111";
//        String levelName = "222";
//        dataModel.put("user", bo);
//        dataModel.put("mental", mental);
//        dataModel.put("lingGen", lingGen);
//        dataModel.put("levelName", levelName);
//        // 渲染模板并将结果输出到字符串中
//        StringWriter writer = new StringWriter();
//        template.process(dataModel, writer);
//        FileOutputStream fileOutputStream = new FileOutputStream("./src/main/java/com/yowasa/xiuxian/image/html/test.html");
//        fileOutputStream.write(writer.toString().getBytes());
//
//        //设置基本的启动配置,这里选择了‘有头’模式启动
//        ArrayList<String> argList = new ArrayList<>();
//        //自动下载，第一次下载后不会再下载
//        BrowserFetcher.downloadIfNotExist(null);
//        LaunchOptions options = new LaunchOptionsBuilder().withArgs(argList).withHeadless(false).build();
//        argList.add("--no-sandbox");
//        argList.add("--disable-setuid-sandbox");
//        Browser browser = Puppeteer.launch(options);
//        BrowserFetcher.downloadIfNotExist(null);
//        Page page = browser.newPage();
//        page.goTo("D:\\xiuxianHub\\mihoyo-mys-bot\\mysBot\\src\\main\\java\\com\\yowasa\\xiuxian\\image\\html\\test.html");
//        ScreenshotOptions screenshotOptions = new ScreenshotOptions();
//        //设置截图范围
//        Clip clip = new Clip(3.0, 1.56, 800, 1600);
//        screenshotOptions.setClip(clip);
//        //设置存放的路径
//        screenshotOptions.setPath("test.png");
//        page.screenshot(screenshotOptions);
//
//
//    }

    public static boolean screenShotWx(String url, String path) throws IOException, ExecutionException, InterruptedException {
        ArrayList<String> arrayList = new ArrayList<>();
        BrowserFetcher.downloadIfNotExist(null);
        LaunchOptions options = new LaunchOptionsBuilder().withArgs(arrayList).withHeadless(true).withIgnoreHTTPSErrors(true).build();
        arrayList.add("--no-sandbox");
        arrayList.add("--disable-setuid-sandbox");
        arrayList.add("--profile-directory=Default");
        arrayList.add("--ignore-certificate-errors");
        arrayList.add("--disable-gpu");
        arrayList.add("--disable-web-security");
        arrayList.add("--disable-infobars");
        arrayList.add("--disable-extensions");
        arrayList.add("--disable-bundled-ppapi-flash");
        arrayList.add("--allow-running-insecure-content");
        arrayList.add("--mute-audio");
        Browser browser = Puppeteer.launch(options);

        // MacOS 要这样写，指定Chrome的位置
        //String executablePath = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
        // LaunchOptions options = new LaunchOptionsBuilder().withExecutablePath(executablePath).withArgs(arrayList).withHeadless(true).withIgnoreHTTPSErrors(true).build();
        // Windows 和 Linux 这样就可以，不用指定 Chrome 的安装位置
//        LaunchOptions options = new LaunchOptionsBuilder().withArgs(arrayList).withHeadless(true).withIgnoreHTTPSErrors(true).build();

        Page page = browser.newPage();
        page.setJavaScriptEnabled(true);
      //  page.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36 Edg/83.0.478.37");
        page.setCacheEnabled(true);
        page.onConsole((msg) -> {});
        PageNavigateOptions pageNavigateOptions = new PageNavigateOptions();
        pageNavigateOptions.setTimeout(100000);
        //dom加载完毕就算导航完成
        pageNavigateOptions.setWaitUntil(Collections.singletonList("domcontentloaded"));
        page.goTo(url, pageNavigateOptions, true);
        autoScroll(page);
        ElementHandle body = page.$("body");
        double width = body.boundingBox().getWidth();
        double height = body.boundingBox().getHeight();
        Viewport viewport = new Viewport();
        viewport.setWidth((int) width);
        // 设置视口宽度
        viewport.setHeight((int) height + 100);
        // 设置视口高度
        page.setViewport(viewport);
        ScreenshotOptions screenshotOptions = new ScreenshotOptions();
        screenshotOptions.setType("jpeg");
        screenshotOptions.setFullPage(Boolean.FALSE);
        Clip clip = new Clip(1.0, 1.56, width, height);
        screenshotOptions.setClip(clip);
        screenshotOptions.setPath(path);
        screenshotOptions.setQuality(100);
        page.screenshot(screenshotOptions);

        browser.close();
        return true;


    }


    private static void autoScroll(Page page) {
        if (page != null) {
            try {
                page.evaluate("() => {\n" + "   return new Promise((resolve, reject) => {\n" + "            //滚动的总高度\n" + "            let totalHeight = 0;\n" + "            //每次向下滚动的高度 500 px\n" + "            let distance = 500;\n" + "            let k = 0;\n" + "            let timeout = 1000;\n" + "            let url = window.location.href;\n" + "            let timer = setInterval(() => {\n" + "                //滚动条向下滚动 distance\n" + "                window.scrollBy(0, distance);\n" + "                totalHeight += distance;\n" + "                k++;\n" + "                console.log(`当前第${k}次滚动，页面高度: ${totalHeight}`);\n" + "                //页面的高度 包含滚动高度\n" + "                let scrollHeight = document.body.scrollHeight;\n" + "                //当滚动的总高度 大于 页面高度 说明滚到底了。也就是说到滚动条滚到底时，以上还会继续累加，直到超过页面高度\n" + "                if (totalHeight >= scrollHeight || k >= 200) {\n" + "                    clearInterval(timer);\n" + "                    resolve();\n" + "                    window.scrollTo(0, 0);\n" + "                }\n" + "            }, timeout);\n" + "        })\n" + "  }");
            } catch (Exception e) {
            }
        }
    }

    public static void main(String[] args) throws Exception {
//        screenShotWx("C:\\opt\\html\\1693019533170.html", "C:\\Users\\yoto\\Desktop\\fujian\\wx.jpg");
        screenShotWx("D:\\xiuxianHub\\mihoyo-mys-bot\\mysBot\\target\\classes\\image\\gen\\1693029110609.html", "C:\\Users\\yoto\\Desktop\\fujian\\wx.jpg");
    }
}